package com.lingx.web.api.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.lingx.service.MethodService;
import com.lingx.utils.TokenUtils;
import com.lingx.web.api.IApi;
@Component
public class Api8004 extends AbstractAuthApi implements IApi{
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private MethodService methodService;
	@Override
	public int getApiCode() {
		return 8004;
	}
	@Override
	public String getApiName() {
		return "获取菜单列表";
	}
	public boolean isLog() {
		return false;
	}
	@Override
	public Map<String, Object> api(Map<String, Object> params) {
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		String token=IApi.getParamString(params, "lingxtoken", "");
		String isename=IApi.getParamString(params, "isename", "false");
		String userid=TokenUtils.getTokenDataUserId(token);
		String menuLinkFunc = " and a.type<>3 and ( a.type<>2 or (a.type=2 and ( func_id in (select func_id from tlingx_user_func where user_id='"+userid+"') or func_id in(select func_id from tlingx_role_func where role_id in(select role_id from tlingx_user_role where user_id='"+userid+"'))))) ";
		String rootId=this.jdbcTemplate.queryForObject("select id from tlingx_menu where fid='0'", String.class);
		ret.put("data", this.menus(rootId,userid,menuLinkFunc,"true".equals(isename)));
		return ret;
	}

	private List<Map<String,Object>> menus(String fid,String userid,String menuLinkFunc,boolean isEname){
		//List<Map<String,Object>> list=this.jdbcTemplate.queryForList("select id,name title,icon_cls icon,func_id from tlingx_menu where fid=? order by orderindex asc",fid);
		
		List<Map<String, Object>> list = jdbcTemplate
				.queryForList("select t.id,t.name as title,t.short_name,t.icon_cls as icon,t.type,a.module ecode,a.func mcode from tlingx_menu t,tlingx_func a where t.func_id=a.id and t.fid=? and t.status=1 and (t.id in(select menu_id from tlingx_user_menu where user_id='"+userid+"') or t.id in(select menu_id from tlingx_role_menu where role_id in(select role_id from tlingx_user_role where user_id='"
						+ userid + "'))) "+menuLinkFunc+" order by t.orderindex asc",fid);
		
		for(Map<String,Object> map:list) {
			map.put("children", menus(map.get("id").toString(),userid,menuLinkFunc,isEname));
			try {
				String template= this.methodService.getMethod(map.get("mcode").toString(), map.get("ecode").toString()).getViewUri();
				if(isEname) {
					map.put("index", template+"?ecode="+map.get("ecode")+"&mcode="+map.get("mcode")+"&ename="+map.get("title"));
				}else {
					map.put("index", template+"?ecode="+map.get("ecode")+"&mcode="+map.get("mcode"));//+"&ename="+map.get("title")
				}
			} catch (Exception e) {
			}
			
		}
		return list;
	}
}
